﻿using System;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Windows.Forms;

namespace NDK.Utils
{
    // public delegate void ListenData
    public class ReseiveDataStruct
    {
        public Socket socket = null;
        public static int bufferSize = 1000;
        public byte[] buffer = new byte[bufferSize];//接受到的数据
    }

    /// <summary>
    /// 服务器端Socket通信类
    /// </summary>
    public class AsySockets
    {
        private static log4net.ILog m_Logger = log4net.LogManager.GetLogger("AsySockets");
        public delegate void ReceiveDataCompleteHandler(string strdata);
        public event ReceiveDataCompleteHandler ReceiveDataCompleteEvent;
        private Socket socketObject = null;
        private string mid = string.Empty;

        public AsySockets(Socket socket)
        {
            socketObject = socket;
            mid = Guid.NewGuid().ToString();
        }

        /// <summary>
        /// 创建Socket实例
        /// </summary>
        /// <param name="addressFamily"></param>
        /// <param name="socketType"></param>
        /// <param name="protocolType"></param>
        public AsySockets()
        {
            socketObject = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            mid = Guid.NewGuid().ToString();
        }

        public void ConnectServer(string IPString, int port)
        {
            if (null == socketObject)
            {
                throw new Exception("Socket对象不为空");
            }
            socketObject.Connect(IPAddress.Parse(IPString), port);
            this.ReceiveData();
        }

        //接受数据
        public void ReceiveData()
        {
            ReseiveDataStruct objectState = new ReseiveDataStruct();

            if (null == socketObject) // 抛异常，外面注意捕获该异常
            {
                throw new Exception("Socket对象不存在");
            }
            objectState.socket = socketObject;
            socketObject.BeginReceive(objectState.buffer, 0, ReseiveDataStruct.bufferSize, SocketFlags.None, new AsyncCallback(ReceiveData_CallBack), objectState);
        }

        //数据接受完毕后
        private void ReceiveData_CallBack(IAsyncResult iar)
        {
            // MessageBox.Show("客户端数据接受完毕！");
            try
            {
                int data = socketObject.EndReceive(iar);
                ReseiveDataStruct objState = iar.AsyncState as ReseiveDataStruct;
                if (data > 0) //数据大于0
                {
                    if (ReceiveDataCompleteEvent != null)
                    {
                        ReceiveDataCompleteEvent(Encoding.Default.GetString(objState.buffer));
                    }
                    //MessageBox.Show(UTF8Encoding.Default.GetString(objState.buffer));
                    //其他相关处理
                }
                objState.buffer = new byte[ReseiveDataStruct.bufferSize];
                socketObject.BeginReceive(objState.buffer, 0, ReseiveDataStruct.bufferSize, SocketFlags.None, new AsyncCallback(ReceiveData_CallBack), objState);
            }
            catch (SocketException sex)
            {
                MessageBox.Show("ReceiveData_CallBack SocketException "+sex.ToString());
                this.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show("ReceiveData_CallBack " + ex.ToString());
            }
        }

        public void SendData(string data,string serverName="Server")
        {
            try
            {
                if (string.IsNullOrEmpty(data))
                {
                    return;
                }
                this.SendData(Encoding.Default.GetBytes(data/* + "\r\n"*/));
                if (!data.ToUpper().Contains("HEART"))
                    m_Logger.Info("To Server:" + data);

            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.StackTrace);
            }

        }
        //发送数据
        public void SendData(byte[] sdata)
        {
            if (null == socketObject)
            {
                throw new Exception("Socket对象为空");
            }
            if (null == sdata)
            {
                return;
            }
            socketObject.BeginSend(sdata, 0, sdata.Length, SocketFlags.None, new AsyncCallback(SendData_CallBack), socketObject);
        }

        public void SendData_CallBack(IAsyncResult ir)
        {
            try
            {
                //数据发送完毕
                if (null != socketObject)
                {
                    socketObject.EndSend(ir);
                }
            }
            catch (SocketException sex)
            {
                MessageBox.Show("SendData_CallBack SocketException " + sex.ToString());
                this.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show("SendData_CallBack  " + ex.ToString());
            }
        }

        public bool? isSocketConnected()
        {
            try
            {
                if (null != socketObject)
                {
                    if (socketObject.Connected)
                        return true;
                    else
                        return false;
                }
                else
                {
                    return null;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Get Socket Connected Status Exception  " + ex.ToString());
                return false;
            }

        }

        public void Close()
        {
            if (socketObject.Connected)
            {
                socketObject.Close();
            }
        }

    }
}

